package com.wuyb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaban.analysis.jieba.JiebaSegmenter;
import com.wuyb.mapper.ChatFilterMapper;
import com.wuyb.mapper.MeetingChatMapper;
import com.wuyb.pojo.ChatFilter;
import com.wuyb.pojo.MeetingChat;
import com.wuyb.pojo.entity.BaseResponse;
import com.wuyb.pojo.entity.ResultUtils;
import com.wuyb.service.MeetingChatService;
import com.wuyb.service.UserFriendInformService;
import com.wuyb.util.FileUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: wyb
 * @Date: 2024/01/02/14:39
 * @Description:
 */
@Service
@Slf4j
public class MeetingChatServiceImpl extends ServiceImpl<MeetingChatMapper, MeetingChat> implements MeetingChatService {

    @Resource
    private MeetingChatMapper meetingChatMapper;

    @Resource
    private UserFriendInformService userFriendInformService;

    @Resource
    private FileUtil fileUtil;

    @Override
    public void insert(String meetingId, Integer userId, String message) {
        meetingChatMapper.insert(new MeetingChat().setMeetingId(meetingId).setUserId(userId).setSendTime(LocalDateTime.now()));
    }

    @Override
    public BaseResponse<?> selectChatJieBa() {
        // 获取停用词文件
        Path stopWordPath = Objects.requireNonNull(fileUtil.getStaticResPathUrl()).resolve("stopwords.txt");
        List<String> stopWords = null;
        try {
            stopWords = Files.readAllLines(stopWordPath);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        // 获取JieBa分词对象
        JiebaSegmenter jiebaSegmenter = new JiebaSegmenter();
        // 获取所有好友的消息
        List<Object> allContent = userFriendInformService.getAllContent();
        // 获取所有会议消息
        List<Object> msg = meetingChatMapper.selectObjs(new QueryWrapper<MeetingChat>()
                .select("msg_xq"));
        allContent.addAll(msg);
        Map<String, Integer> map = new HashMap<>();

        for (Object str : allContent) {
            // 去掉中文以外的字符
            String replaceStr = str.toString().replaceAll("[^\\u4e00-\\u9fa5]", "");
            for (String sstr : jiebaSegmenter.sentenceProcess(replaceStr)) {
                if (filterStopWord(stopWords, sstr)) {
                    continue;
                }
                if (map.containsKey(sstr)) {
                    map.put(sstr, map.get(sstr) + 1);
                } else {
                    map.put(sstr, 1);
                }
            }
        }

        return ResultUtils.success(map);
    }

    /**
     * 如果一句当中包含敏感词就返回真
     *
     * @param stopWords
     * @param str
     * @return
     */
    private boolean filterStopWord(List<String> stopWords, String str) {
        if (stopWords == null) {
            return false;
        }
        return stopWords.contains(str);
    }

    @Override
    public BaseResponse<?> selectStopWord() {
        Path stopWordPath = Objects.requireNonNull(fileUtil.getStaticResPathUrl()).resolve("stopwords.txt");
        List<String> strings = null;
        try {
            strings = Files.readAllLines(stopWordPath);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return ResultUtils.success(strings);
    }

    @Override
    public BaseResponse<String> updateStopWord(List<String> words) {
        Path stopwordPath = Objects.requireNonNull(fileUtil.getStaticResPathUrl()).resolve("stopwords.txt");
        byte[] bytes = String.join("\n", words).getBytes();

        try {
            OutputStream outputStream = new FileOutputStream(stopwordPath.toString());
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return ResultUtils.success("保存成功");
    }
}
